import json

from sqlalchemy.exc import SQLAlchemyError

from common.ApiResponse import ApiResponse
from common.BaseResponse import BaseResponse
from common.ErrorCode import ErrorCode
from models import App, UserAnswer, Question, ScoringResult, db


def doGradeScore(choices: list[str], app: App, id:int) -> UserAnswer:
    appId = app.id
    question = Question.query.filter(Question.appId == appId).first()
    # 假设 ScoringResult 类和 db 已经正确导入
    scoringResultList: list[ScoringResult] = ScoringResult.query.filter(
        ScoringResult.appId == appId
    ).filter(ScoringResult.isDelete==0).order_by(ScoringResult.resultScoreRange.desc()).all()
    if not isinstance(question, Question):
        print("question参数类型错误哦")
        baseResponse = BaseResponse.from_error_code(ErrorCode.OPERATION_ERROR)
        return ApiResponse.error_from_baseResponse(baseResponse=baseResponse, data="参数类型错误")

    if not isinstance(scoringResultList, list):
        print("scoringResultList 参数不是列表类型哦")
        baseResponse = BaseResponse.from_error_code(ErrorCode.OPERATION_ERROR)
        return ApiResponse.error_from_baseResponse(baseResponse=baseResponse, data="参数类型错误")
        # 检查列表中的每个元素是否为 ScoringResult 类型
    for item in scoringResultList:
        if not isinstance(item, ScoringResult):
            print("scoringResultList 列表中的元素类型错误哦")
            baseResponse = BaseResponse.from_error_code(ErrorCode.OPERATION_ERROR)
            return ApiResponse.error_from_baseResponse(baseResponse=baseResponse, data="参数类型错误")
    questionContent = question.questionContent
    questionContentList = json.loads(questionContent)
    totalScore = 0
    if len(questionContentList) != len(choices):
        print("题目和用户答案数量不匹配")
        baseResponse = BaseResponse.from_error_code(ErrorCode.PARAMS_ERROR)
        return ApiResponse.error_from_baseResponse(baseResponse=baseResponse, data="题目和用户答案数量不匹配")
    for index, questionContent in enumerate(questionContentList):
        options: list = questionContent.get("options")
        scoreMap = {
            option.get('key'): int(option.get('score')) for option in options
        }
        choice = choices[index]
        score = scoreMap.get(choice, 0)
        totalScore += score

    maxScoringResult = scoringResultList[len(scoringResultList)-1]
    for index,scoreResult in enumerate(scoringResultList):
        if totalScore > scoreResult.resultScoreRange:
            maxScoringResult = scoringResultList[index]
            break
    try:
        userAnswer: UserAnswer = UserAnswer.query.get(id)
        userAnswer.appId = maxScoringResult.appId
        userAnswer.appName = app.appType
        userAnswer.score = app.scoringStrategy
        userAnswer.choices = json.dumps(choices, ensure_ascii=False, indent=4) # 存入数据库的比如是A,B,C,D之类的
        userAnswer.resultScore = totalScore
        userAnswer.resultDesc = maxScoringResult.resultDesc
        userAnswer.resultName = maxScoringResult.resultName
        userAnswer.resultPicture = maxScoringResult.resultPicture
        db.session.commit()
        return userAnswer
    except SQLAlchemyError as e:
        print(f"测评类用户添加失败:{str(e)}")
        db.session.rollback()
        baseResponse = BaseResponse.from_error_code(ErrorCode.OPERATION_ERROR)
        return ApiResponse.error_from_baseResponse(baseResponse=baseResponse, data=str(e))
